import queue
import threading
import time


class MyThread(threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q

    def run(self):
        print("开启线程: {}".format(self.name))
        processData(self.name, self.q)
        print("退出线程：{}".format(self.name))


def processData(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            print("{} processing {}".format(threadName, data))
            queueLock.release()
        else:
            queueLock.release()
        time.sleep(1)


exitFlag = False
queueLock = threading.Lock()
workQueue = queue.Queue(10)


def runThread():
    threadList = ["Thread-1", "Thread-2", "Thread-3"]
    nameList = ["One", "Two", "Three", "Four", "Five"]
    threads = []
    threadID = 1

    for tName in threadList:
        thread = MyThread(threadID, tName, workQueue)
        thread.start()
        threads.append(thread)
        threadID += 1

    queueLock.acquire()
    for word in nameList:
        workQueue.put(word)
    queueLock.release()

    while not workQueue.empty():
        pass
    
    global exitFlag
    exitFlag = True
    for t in threads:
        t.join()
    print("退出主线程")


if __name__ == "__main__":
    runThread()

